package com.cykj.service.impl;

import com.cykj.dto.ResponseDTO;
import com.cykj.entity.AdminDO;
import com.cykj.mapper.AdminMapper;
import com.cykj.service.IAdminService;
import com.cykj.utils.JwtUtil;
import com.cykj.utils.MD5Util;
import com.cykj.vo.AdminVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 王宇
 * @CreateTime: 2025-07-28  09:21
 * @BelongsProject: jd_seckill
 * @BelongsPackage: com.cykj.service.impl
 * @description 管理员服务接口实现
 */
@Service
public class IAdminServiceImpl implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public ResponseDTO login(AdminVO adminVO) {
        if (adminVO.getAdminPassword() != null && !adminVO.getAdminPassword().isEmpty()) {
            adminVO.setAdminPassword(MD5Util.encrypt(adminVO.getAdminPassword()));
        }
        AdminDO adminDO = adminMapper.login(adminVO);
        if (adminDO != null) {
            // 根据用户id，用户昵称，用户头像路径生成token
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("adminId", adminDO.getAdminId());
            hashMap.put("adminName", adminDO.getAdminName());
            hashMap.put("adminIcon", adminDO.getAdminIcon());
            String token = JwtUtil.generateJwt(hashMap);
            hashMap.put("token", token);
            redisTemplate.opsForValue().set(token, adminDO, 30, TimeUnit.MINUTES);
            return ResponseDTO.success("登录成功", hashMap);
        }
        return ResponseDTO.error("账号或密码错误");
    }
}
